from random import choice
from vehicle import Vehicle

class Node(object):
	def __init__(self):
		pass

	def update(self):
		pass

	def requota(self):
		pass

class GenNode(Node):
	def __init__(self, next):
		self.next = next

	def update(self):
		v = Vehicle()
		while self.next.inject(v):
			v =Vehicle()

class SunkNode(Node):
	def __init__(self, period):
		self.period = period
		self.timer = 0
		self.block = True

	def update(self):
		self.timer += 1
		if self.timer >= self.period:
			self.timer = 0
			self.block = not self.block

	def inject(self, vehicle):
		if self.block:
			return False
		else:
			return True

class ODNode(object):
	def __init__(self, rate = 3.0):
		self.rate = rate
		self.out_connectors = {}
		self.quota = rate
	def requota(self):
		if self.quota < 0.0:
			self.quota += self.rate

	def update(self):
		while self.quota >= 0.0:
			veh = Vehicle()
			connector = choice(self.out_connectors.values())
			if connector.inject(veh):
				self.quota -= 1.0
			else:
				return

	def inject(self, vehicle, linkid):
		return true

	def add_in_link(self, linkid, inlink):
		pass

	def add_out_link(self, linkid, outlink):
		self.out_connectors[linkid] = outlink

class InterNode(object):
	def __init__(self, cycle = 100):
		self.in_links = {}
		self.out_links = {}
		self.time = 0
		self.cycle = cycle
		
		self.buffer = []
		self.current = 0

	def requota(self):
		self.current = int(float(self.time)/float(self.cycle)*len(self.in_links))

	def update(self):
		self.time += 1
		if self.time >= self.cycle:
			self.time = 0
		temp = []
		for vehicle in self.buffer:
			out_link = choice(self.out_links.values())
			if not out_link.inject(vehicle):
				temp.append(vehicle)

		self.buffer = temp

	def inject(self, vehicle):
		linkid = vehicle.linkid
		if self.in_links.keys()[self.current] != linkid:
			return False
		elif len(self.buffer) > 10:
			return False
		else:
			self.buffer.append(vehicle)
			return True

	def add_in_link(self, linkid, inlink):
		self.in_links[linkid] = inlink

	def add_out_link(self, linkid, outlink):
		self.out_links[linkid] = outlink
